package cn.maxmc.murderaddons.task

import cn.maxmc.murderaddons.MurderAddons
import cn.maxmc.murderaddons.logger
import io.izzel.taboolib.module.config.TConfig
import io.izzel.taboolib.module.locale.TLocale
import org.bukkit.configuration.file.YamlConfiguration
import plugily.projects.murdermystery.arena.Arena
import plugily.projects.murdermystery.arena.ArenaRegistry
import java.io.File
import kotlin.collections.ArrayList

object ArenaTaskManager {

    val tasks = ArrayList<ArenaTask>()
    val tasksCache = HashMap<Arena,ArenaTask>()

    init {
        ArenaRegistry.getArenas().forEach {
            val file = File(File(MurderAddons.plugin.dataFolder, "data"), "${it.id}.yml")
            // filter Arenas
            if (!file.exists()) {
                return@forEach
            }
            val yaml = YamlConfiguration().also { cfg -> cfg.load(file) }

            try {
                val task = yaml.get("data") as ArenaTask
                tasks.add(task)
                tasksCache[it] = task
            }catch (e: Throwable) {
                logger.error(TLocale.asString("failed_load", it.id))
                return@forEach
            }
        }
    }

    fun addTask(task: ArenaTask) {
        if(tasks.contains(task)) {
            throw IllegalArgumentException("The given task is already exist.")
        }

        saveTask(task)

        tasksCache[task.arena] = task
        tasks.add(task)
    }

    fun saveTask(task: ArenaTask) {
        val dataFile = File(File(MurderAddons.plugin.dataFolder,"data"),"${task.arena.id}.yml")

        if(dataFile.exists()) {
            dataFile.delete()
        }

        if(!dataFile.exists()) {
            dataFile.parentFile.mkdirs()
            dataFile.createNewFile()
        }

        val config = TConfig.create(dataFile)

        config["data"] = task

        config.saveToFile()
    }
}